import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import { focusStore } from "../../store";
import { TypeDirection, TypeKeys } from "@/focus/type";
import { getUUid } from "@/focus/path/until";
import { watchWidgetList } from "./until";
// 定义函数类型
type TypeMoveFn = (_?: TypeDirection) => void;
export default defineComponent({
  name: "focus-box",
  emits: ["moveIn", "moveOut", "move"],
  props: {
    boxId: {
      type: String,
      default: ""
    },
    //传入后moveIn时将优先跳转到该id指定的焦点元素
    cacheId: {
      type: String,
      default: ""
    },
    //是否锁住cacheId，锁住后焦点切换时将不会进行修改，如果cacheId为空则moveIn的时候将会正常跳转
    cacheIdLock: {
      type: Boolean,
      default: false
    },
    onMoveIn: {
      type: Function as unknown as () => TypeMoveFn,
      defalut: (_?: TypeDirection) => { }
    },
    onMoveOut: {
      type: Function as unknown as () => TypeMoveFn,
      defalut: (_?: TypeDirection) => { }
    },
    onMove: {
      type: Function as unknown as () => TypeMoveFn,
      defalut: (_?: TypeDirection) => { }
    },
  },

  setup(props, { emit }) {
    const domRef = ref<HTMLElement>()
    const focusInject = focusStore.inject()
    const uid = ref<string>(props.boxId || getUUid())
    let keyValue: (keyof TypeKeys) | undefined
    //监控子组件中的焦点元素  更新焦点元素中的box信息
    const { onMove, onMoveIn, onMoveOut } = watchWidgetList(props, uid, domRef)
    onMove(() => emit("move", keyValue))
    onMoveIn(() => emit("moveIn", keyValue))
    onMoveOut(() => emit("moveOut", keyValue))
    const timer: { value?: any } = { value: undefined }
    onMounted(() => {
      focusInject.listenerKeyDown(uid.value, (ev) => {
        clearTimeout(timer.value)
        keyValue = ev
        timer.value = setTimeout(() => {
          keyValue = undefined
        }, 6);
      })
    })
    onUnmounted(() => {
      clearTimeout(timer.value)
      focusInject.unListenerKeyDown(uid.value)
    })
    return {
      domRef,
      uid,
    }
  },
  render() {
    return (
      <div ref="domRef" id={this.uid}>
        {this.$slots.default}
      </div>
    );
  }
})
